package com.saasitems.common.utils;

import java.io.*;
import java.net.URL;
import java.util.Properties;

public class PropertiesUtil {

	private Properties prop = null;
	private static PropertiesUtil propUtil;
	public static PropertiesUtil newInstance(){
		if(propUtil == null){
			propUtil = new PropertiesUtil();
		}
		return propUtil;
	}
	private PropertiesUtil() {
		prop = new Properties();//属性集合对象    
		InputStream is = null;
		try {
			// String path = ClassLoader.getSystemResource("com/itec/util/evn.properties").getPath();
			// is = this.getClass().getClassLoader().getResourceAsStream("env.properties");
			URL url = Thread.currentThread().getContextClassLoader().getResource("");
			String realpath = url.getPath() + "env.properties";

			String os = System.getProperty("os.name");
			if(os.toLowerCase().startsWith("win")){
				realpath = realpath.substring(1);
			} else {
			}
			System.out.println("realpath: " + realpath);
			is = new FileInputStream(realpath);
			prop.load(is);//将属性文件流装载到Properties对象中
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
			try {
				if(is != null){
					is.close();					
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 通过左边属性名称取得属性值
	 * @param key
	 * @return
	 */
	public String getStringByKey(String key) {
		if (this.prop == null) 
			return "";
		
		return this.prop.getProperty(key);
	}
	/**
	 * 通过左边属性名称取得属性值
	 * 如果没有改文件夹目录，床架该文件夹
	 * @param
	 * @return 属性值
	 * */
	public String getDirNameByKey(String dirKey){
		String dirName = "";
		if (this.prop == null) {
			return "";
		}else{
			dirName = this.prop.getProperty(dirKey);
			File dir = new File(dirName);
			// 判断文件夹是否存在,如果不存在则创建文件夹
			if (!dir.exists()) {
				dir.mkdir();
			}
		}
		return dirName;
	}
}
